/**
 * ID卡的发卡页面, ID发卡器使用USB键盘驱动，发卡时卡号自动出现在光标处
 */

class IDForSave extends React.Component {
    constructor(props) {
        super(props);
        this.cardObj = props.ActiveX;
        this.defaultSection = 14;
        this.ownerSelected = {};
        this.state = {
            owners: [''],
            perms: [],
            cardInfo: {},
            devNum: 0,
            staffNodes: null,
            IDCode: ""
        };

        this.IDCache = "";
        this.timeout = null;
    }

    componentDidMount() {
        //这里必须要，不然光标在菜单上第一次不能获取卡号
        this.refs.normalCardNo.refs.input.focus();
        document.onkeydown = (ev) => {
            /* 过滤调 0-9 a-z A-Z 以外的按键 */
            if (ev.keyCode >= 48 && ev.keyCode <= 57 || ev.keyCode >= 65 && ev.keyCode <= 90 ||
                ev.keyCode >= 97 && ev.keyCode <= 122) {
                if (this.IDCache.length === 1)
                    layui.layer.load(2);
                this.IDCache += ev.key;
                if (this.timeout)
                    clearTimeout(this.timeout);

                this.timeout = setTimeout(() => {
                    layui.layer.closeAll('loading');
                    if (this.IDCache.length >= 6)
                        this.setState({IDCode: this.IDCache}, () => {
                            this.readCardNo(this.IDCache);
                            this.IDCache = "";
                        });
                    else
                        this.IDCache = "";
                }, 500)
            }
            return false;
        }
    }

    /**
     * 读取卡号,同时从卡信息中读取业主相关信息
     * @param type
     */
    readCardNo(cardNo) {

        postJson("/card/findCard.x", {cardNo: cardNo}, (data) => {
            let cardInfo = data.data.cardInfo;
            if (cardInfo) {
                this.ownerSelected.ownerCode = cardInfo.ownerCode;
                this.ownerSelected.ownerName = cardInfo.ownerName;
                this.ownerSelected.roomInfoNum = cardInfo.roomName;
                this.ownerSelected.commCode = cardInfo.commCode;
                this.refs.superDate.value = this.refs.normalDate.value = cardInfo.endDate ? cardInfo.endDate.substr(0, 10) : '';
                if (cardInfo.cardType == 's') {
                    this.refs.scommSelect.commCode = cardInfo.commCode;
                    this.refs.staffName.value = cardInfo.ownerName;
                    layui.layer.msg("超级卡");
                }

                this.refs.tab.changeTab(cardInfo.cardType);
            } else {
                layui.layer.msg("未找到授权信息");
            }
            this.setState({
                ownerStr: data.data.ownerStr,
                perms: data.data.cardPerms,
                cardInfo: cardInfo ? cardInfo : {}
            })
        })

    }

    resumeCard(type) {

        if (!this.refs[type + 'CardNo'].value) {
            layui.layer.alert("请先读取卡", {icon: 5});
            return;
        }

        if (type == 'normal' && (!this.state.perms || this.state.perms.length == 0)) {
            layui.layer.alert("未读取到权限记录,无法恢复", {icon: 5});
            return;
        } else if (type == 'super' && (!this.refs.scommSelect.commCode)) {
            layui.layer.alert("请选择小区", {icon: 5});
            return;
        }

        let param = {cardNo: this.refs[type + 'CardNo'].value};
        postJson("/card/resumeCard.x", param, function () {
            layui.layer.alert("卡恢复成功!");
        })

    }

    selectOwnerDlg() {
        this.refs.selectOwner.show();
    }

    selectDevDlg() {
        this.refs.selectDev.show();
    }

    onChangeRoom() {
        let commSelect = this.refs.commSelect;
        let roomInfoNum = commSelect.commCode + commSelect.buildingCode + commSelect.unitCode + commSelect.floorCode + commSelect.roomCode;

        postJson("/owner/findOwnerByRoom.x", {roomCode: roomInfoNum}, (data) => {
            this.setState({owners: data.data});
        })
    }

    onChangeUnit() {
        if (!this.refs.devSelect.unitCode)
            return;
        let params = {
            commCode: this.refs.devSelect.commCode,
            buildingCode: this.refs.devSelect.buildingCode,
            unitCode: this.refs.devSelect.unitCode
        }

        postJson("/building/getUnitDevNum.x", params, (data) => {
            this.setState({devNum: data.data});
        })
    }

    selectOwner() {
        let ownerCode = this.refs.ownerSelect.value;
        for (let i = 0; i < this.state.owners.length; i++) {
            console.log("ownercode " + ownerCode + " owner " + this.state.owners[i].ownerCode);
            if (ownerCode == this.state.owners[i].ownerCode) {
                this.ownerSelected = this.state.owners[i];
                this.state.ownerStr = this.ownerSelected.roomInfo + " " + this.ownerSelected.ownerName;
                break;
            }
        }

        if (this.refs.defaultPerms.checked) {
            let param = {ownerCode: this.ownerSelected.ownerCode};
            postJson("/card/getDefaultPerms.x", param, (data) => {
                this.setState({perms: data.data});
                this.refs.selectOwner.close();
            })
        } else {
            this.refs.selectOwner.close();
            this.setState({perms: ['']});
        }

        return false;
    }

    downloadPlugins() {
        layui.layer.msg("不需要下载插件");
    }

    addNewPerms(perm) {
        for (let i = 0; i < this.state.perms.length; i++) {
            if (this.state.perms[i].devBuildingNo == perm.devBuildingNo)
                return;
        }

        this.state.perms.push(perm);
    }

    /* 将设备号转换为IC卡权限设备号 ,由于IC卡内部使用2个字节表示一个设备号,因此将16个字节拆分成3个区域
			栋数  - 单元号 - 设备号
			9字节      4字节        3字节

			因此可以支持512栋， 每栋16单元，每单元8个设备 .
			围墙机号码,使用栋数单元数为0即可
		*/
    getDevNumber(areaCodeInt, buildingCodeInt, devNumInt) {
        let result = (areaCodeInt << 7) | (buildingCodeInt << 3) | devNumInt;
        let resultStr = result.toString(16);

        if (resultStr.length === 2)
            resultStr = "00" + resultStr;
        else if (resultStr.length === 3)
            resultStr = "0" + resultStr;

        return resultStr;
    }

    selectDev() {
        let areaCodeInt = this.refs.devSelect.buildingCode;
        let buildingCodeInt = this.refs.devSelect.unitCode;
        let devNumInt = this.state.devNum;
        for (let i = 1; i <= devNumInt; i++) {
            let perm = {};
            perm.devNo = this.getDevNumber(areaCodeInt, buildingCodeInt, i);
            perm.devStr = '[' + this.refs.devSelect.commText + "] " + this.refs.devSelect.buildingText + " " + this.refs.devSelect.unitText + " " + i + "号机 ";
            perm.devBuildingNo = this.refs.devSelect.commCode + this.refs.devSelect.buildingCode + this.refs.devSelect.unitCode + "000" + i;
            this.addNewPerms(perm);
        }

        this.setState({perms: this.state.perms});
        this.refs.selectDev.close();
        return false;
    }

    removePerm(index) {
        this.state.perms.splice(index, 1);
        this.setState({perms: this.state.perms});
    }

    getCommCode(type) {
        if (type == 'super')
            return this.refs.scommSelect.commCode;

        if (this.ownerSelected.commCode)
            return this.ownerSelected.commCode;
        else if (this.refs.scommSelect.commCode)
            return this.refs.scommSelect.commCode;
        else
            return this.state.cardInfo.commCode;
    }

    /**
     * 发普通卡
     * @returns {boolean}
     */
    publishNormalCard() {

        if (!this.state.ownerStr) {
            layui.layer.alert("请选择业主");
            return false;
        }
        if (this.state.perms.length == 0) {
            layui.layer.alert("请选择权限");
            return false;
        }

        if (this.state.perms.length > 8) {
            layui.layer.alert("目前一张卡只能支持8个门!", {icon: 5});
            return false;
        }

        let params = {
            ownerCode: this.ownerSelected.ownerCode,
            ownerName: this.ownerSelected.ownerName,
            roomName: this.ownerSelected.roomInfoNum,
            commCode: this.ownerSelected.commCode,
            cardType: 'n',
            nState: '01',
            nCardNo: this.refs.normalCardNo.value,
            endDate: this.refs.normalDate.value,
            permsStr: []
        };

        for (let i = 0; i < this.state.perms.length; i++)
            params.permsStr[i] = ('x:' + this.state.perms[i].devNo + ":" + this.state.perms[i].devStr + ":" + this.state.perms[i].devBuildingNo);

        postAJson("/card/save.x", params, (data) => {
            layer.msg("发卡成功!");
        })

        return false;
    }

    /**
     * 发超级卡
     * @returns {boolean}
     */
    publishSuperCard() {

        if (!this.refs.scommSelect.commCode) {
            layui.layer.alert("请选择小区", {icon: 5});
            return;
        }

        let params = {
            ownerCode: "",
            ownerName: this.refs.staffName.value,
            roomName: "",
            cardType: 's',
            sState: '01',
            commCode: this.refs.scommSelect.commCode,
            sCardNo: this.refs.superCardNo.value,
            endDate: this.refs.superDate.value
        };

        postJson("/card/save.x", params, () => {
            layer.msg("发卡成功!");
        })

        return false;
    }

    cancel() {
        history.back(-1);
    }

    selectStaff() {
        if (!this.state.staffNodes) {
            let commCode = this.refs.scommSelect.commCode;
            postJson("/property/org/getList.x", {commCode: commCode}, (data) => {
                let orgsData = data.data;
                postJson("/property/staff/getByComm.x", {commCode: commCode}, (data) => {
                    let staffDatas = data.data;
                    for (let i = 0; i < staffDatas.length; i++) {
                        staffDatas[i].parentId = staffDatas[i].orgId;
                        staffDatas[i].iconclass = "fa fa-user";
                        staffDatas[i].orgName = staffDatas[i].staffName;
                        staffDatas[i].id = staffDatas[i].orgId + "-" + staffDatas[i].staffId;
                    }

                    staffDatas.push(...orgsData);
                    let staffNodes = this.refs.staffTreeModal.getNodes(staffDatas, null, 'parentId', 'id', 'orgName');

                    this.setState({staffNodes: staffNodes}, () => {
                        this.refs.staffTreeModal.show({typeData: this.refs.staffName.inputRef})
                    });
                })

            });
        } else
            this.refs.staffTreeModal.show({typeData: this.refs.staffName.inputRef})
    }

    managerCommChange() {
        this.state.staffNodes = null;
    }

    render() {
        return (
            <div>
                <Tab titles={['新增普通卡', '新增超级卡']} type="brief" ids={['n', 's']} ref="tab">
                    <TabItem show={true}>
                        <Form size="sm">
                            <Table>
                                <tbody>
                                <tr>
                                    <td width={300}>
                                        门禁卡编号
                                    </td>
                                    <td>
                                        <Input ref="normalCardNo" lay-verify="required" placeHolder="请刷卡"
                                               value={this.state.IDCode}
                                               style={{width: 150, marginRight: 10}}/>
                                        <Button btnType="danger" size="sm" onClick={() => this.resumeCard('normal')}>恢复白卡</Button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属业主</td>
                                    <td>
                                        <Button btnType="normal" size="sm"
                                                onClick={() => this.selectOwnerDlg()}>选择业主</Button>
                                        {this.state.ownerStr ? <span className="layui-badge layui-bg-green"
                                                                     style={{marginLeft: 10}}>{this.state.ownerStr}</span> : ''}
                                    </td>
                                </tr>
                                <tr>
                                    <td>有效期至:</td>
                                    <td><DateSelect placeHolder="不填表示永久有效" ref="normalDate" min={1}/></td>
                                </tr>
                                <tr>
                                    <td>门禁权限&nbsp;&nbsp;&nbsp;
                                        <Button className="layui-btn layui-btn-normal layui-btn-sm"
                                                onClick={() => this.selectDevDlg()}>添加</Button>
                                    </td>
                                    <td>
                                        {
                                            this.state.perms ? this.state.perms.map((perm, index) => {
                                                return (
                                                    <Item>
                                                        <Button className="layui-btn layui-btn-sm layui-btn-danger"
                                                                onClick={() => this.removePerm(index)}>删除</Button>
                                                        <span style={{marginLeft: 10}}>{perm.devStr}</span>
                                                        {index + 1 != this.state.perms.length ? <hr/> : ''}
                                                    </Item>
                                                )
                                            }) : '未查询到该卡权限'
                                        }
                                    </td>
                                </tr>
                                </tbody>
                            </Table>
                            <Button className="layui-btn" onClick={() => this.publishNormalCard()}
                                    lay-submit="true">保存</Button>
                            <Button className="layui-btn layui-btn-normal" onClick={() => this.cancel()}>取消</Button>
                        </Form>
                    </TabItem>
                    <TabItem>
                        <Form size="sm">
                            <Table>
                                <tbody>
                                <tr>
                                    <td width={300}>
                                        门禁卡编号
                                    </td>
                                    <td>
                                        <Input ref="superCardNo" lay-verify="required"
                                               style={{width: 150, marginRight: 10}} placeHolder="请刷卡"
                                               value={this.state.IDCode}/>
                                        <Button btnType="danger" size="sm"
                                                onClick={() => this.resumeCard('super')}>恢复白卡</Button>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属小区</td>
                                    <td>
                                        <LayuiCommSelect mask={['commCode', 'building', 'unit', 'floor', 'room']}
                                                         ref="scommSelect" commCode={this.props.commCode}
                                                         commSelectShowStyle="BadgeWhenOneComm"
                                                         onChangeComm={() => this.managerCommChange()}/>
                                    </td>
                                </tr>
                                <tr>
                                    <td>所属物管员工</td>
                                    <td>
                                        <Item style={{marginBottom: 0}}>
                                            <ButtonInput ref="staffName" placeHolder="默认显示为管理员"
                                                         onClick={() => this.selectStaff()} size="sm"/>
                                            <TreeModal ref="staffTreeModal" nodes={this.state.staffNodes}
                                                       errorStr="未找到管理员数据<br/>请去组织人员管理中创建" onSelected={
                                                (string, data) => {
                                                    if (data.staffId)
                                                        this.refs.staffName.value = string;
                                                    else
                                                        layui.layer.msg("请选择员工");
                                                }
                                            }/>
                                        </Item>
                                    </td>
                                </tr>
                                <tr>
                                    <td>有效期至:</td>
                                    <td><DateSelect placeHolder="不填表示永久有效" ref="superDate" min={1}/></td>
                                </tr>
                                </tbody>
                            </Table>
                            <Button onClick={() => this.publishSuperCard()} lay-submit="true">保存</Button>
                            <Button btnType="normal" onClick={() => this.cancel()}>取消</Button>
                        </Form>
                    </TabItem>
                </Tab>

                <Modal ref="selectOwner" title="楼栋单元选择" offset='100px' area={['1000px']}>
                    <Form size="sm">
                        <Item style={{margin: 10}}>
                            <LayuiCommSelect onChangeRoom={() => this.onChangeRoom()} commCode={this.props.commCode}
                                             mask={['commCode']}
                                             ref="commSelect"/>
                            <Select ref="ownerSelect" lay-verify="required">
                                <option value="">请选择业主</option>
                                {
                                    this.state.owners.map((owner) => {
                                        return <option value={owner.ownerCode}>{owner.ownerName}</option>
                                    })
                                }
                            </Select>
                        </Item>
                        <hr/>
                        <div style={{marginLeft: 100}}>
                            <Checkbox title="自动生成默认权限" checked={true} ref="defaultPerms"/>
                            <Button btnType="normal" size="sm" onClick={() => this.selectOwner()}
                                    lay-submit="true">确认</Button>
                        </div>
                    </Form>
                </Modal>
                <Modal ref="selectDev" title="权限选择" area={['470px']} offset="100px">
                    <Form size="sm">
                        <Item style={{margin: 10}}>
                            <LayuiCommSelect onChangeUnit={() => this.onChangeUnit()} ref="devSelect"
                                             commCode={this.props.commCode}
                                             mask={['commCode', 'floor', 'room']} lay-verify="required"/>
                            <Button btnType="normal" size="sm" lay-submit="true"
                                    onClick={() => this.selectDev()}>确定</Button>
                        </Item>
                    </Form>
                </Modal>
                <a target="downLoadFileFrame" hidden href="/Resource/regCardActiveX.exe" ref="downloadLink"/>
            </div>
        )
    }
}

